package Other;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.mysql.jdbc.ResultSetMetaData;
import com.mysql.jdbc.Statement;



public class DatabaseSQLiteConnection {

	
	public static void main(String[] args) throws Exception {
		 
		 JTable table = new JTable(buildTableModel());
		 JOptionPane.showMessageDialog(null, new JScrollPane(table));
		 
	}
	//The method buildTableModel:

	public static DefaultTableModel buildTableModel() {
		
		Vector<String> columnNames = null;
		Vector<Vector<Object>> data = null;
		 try{
		 Class.forName("com.mysql.jdbc.Driver").newInstance();
		    //connect with the database
		 Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/newtir", "root", "");
	    // The Connection is obtained
		Statement stmt = (Statement) con.createStatement();
	    ResultSet rs = stmt.executeQuery("select * from country");

	
	    ResultSetMetaData metaData = (ResultSetMetaData) rs.getMetaData();

	    // names of columns
	    columnNames = new Vector<String>();
	    int columnCount = metaData.getColumnCount();
	    for (int column = 1; column <= columnCount; column++) {
	        columnNames.add(metaData.getColumnName(column));
	    }

	    // data of the table
	    data = new Vector<Vector<Object>>();
	    while (rs.next()) {
	        Vector<Object> vector = new Vector<Object>();
	        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
	            vector.add(rs.getObject(columnIndex));
	        }
	        data.add(vector);
	    }
	    rs.close();
		stmt.close();
		con.close();
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	    return new DefaultTableModel(data, columnNames);
		
	}
    
}